package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.domain.Notice_Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.mapper.Notice_EmployeeMapper;
import cn.wolfcode.query.Query;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.unit.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private Notice_EmployeeMapper notice_employeeMapper;

    @Override
    public void save(Notice notice) {
        //设置发布人
        notice.setIssuer(UserContext.getUser());
        //设置发布时间
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(Query qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageCount()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        //获取当前用户
        Employee employee= UserContext.getUser();
        //迭代集合,根据用户id和公告id能否返回一个Notice_Employee对象,判断是否已读
        for (Notice notice : notices) {
            Notice_Employee ne=notice_employeeMapper.selectByEmployeeIdNoticeId(employee.getId(),notice.getId());
            if (ne!=null){
                notice.setRead(true);
            }
        }
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void read(Long noticeId) {
        //获取当前登录员工
        Employee employee = UserContext.getUser();;
        //维护员工与公告的关系
        employeeMapper.noticeRelation(employee.getId(),noticeId);
    }
}
